using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Data.OleDb;
using _18miljard.Config;

namespace _18miljard.Db
{
	public class QueryCollection : Collection<Query>
	{
		ConnectionParameters connectionParameters;

		public QueryCollection()
			: this(WebConfig.ConnectionParameters)
		{
		}

		public QueryCollection(ConnectionParameters connectionParameters)
		{
			this.connectionParameters = connectionParameters;
		}

		public void Add(QueryCollection queries)
		{
			foreach (Query query in queries)
				this.Add(query);
		}

		public object Execute()
		{
			if (this.Count == 0)
				return null;

			object retVal = null;

			ConnectionWithTransaction connection = new ConnectionWithTransaction(this.connectionParameters.ConnectionString);

			try
			{
				for (int i = 0; i < this.Count; i++)
				{
					Query query = this[i];

					query.Connection = connection.Connection;

					retVal = query.ExecuteBatch(connection.Transaction);
				}

				connection.Commit();
			}
			catch (OleDbException)
			{
				connection.Rollback();

				retVal = null;
			}
			finally
			{
				connection.Close();
			}

			return retVal;
		}
	}
}
